//
//  DJTableMVVMController.swift
//  dj-learn-Swift
//
//  Created by Sun Jae on 2022/5/10.
//  Copyright © 2022 S.J. All rights reserved.
//

import UIKit

class DJTableMVVMController: DJViewController {

    var viewModel: DJTableTVIewModel?
    
    var tableView: UITableView!
    
    var footerView: DJTableMVVMBottomView!
    
    let nameCell = DJTableTextCell.loadNib()
    
    let hobbyCell = DJTableTextCell.loadNib()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.viewModel = DJTableTVIewModel(
            input: (
                name: nameCell.textField.rx.text.orEmpty.asDriver(),
                gender: hobbyCell.textField.rx.text.orEmpty.asDriver(),
                submitTap: footerView.submitButton.rx.tap.asSignal()
            )
        )
        
        self.viewModel?.signupEnabled.drive(onNext: { enable in
            self.footerView.submitButton.isEnabled = enable
            
        }).disposed(by: self.disposeBag)
    }
    
    override func configSubviews() {
        self.tableView = UITableView(frame: .zero, style: .grouped)
        self.tableView.delegate = self
        self.tableView.dataSource = self
//        self.tableView.register(UINib.init(nibName: "DJTableTextCell", bundle: Bundle.main), forCellReuseIdentifier: "DJTableTextCell")
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.footerView = (Bundle.main.loadNibNamed("DJTableMVVMBottomView", owner: nil, options: nil)?.first as! DJTableMVVMBottomView)
        self.footerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 60.0)
        self.tableView.tableFooterView = self.footerView
        
    }
}

extension DJTableMVVMController : UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel?.items.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            nameCell.model = self.viewModel?.items[indexPath.row]
            return nameCell
            
        default:
            hobbyCell.model = self.viewModel?.items[indexPath.row]
            return hobbyCell
        }
    }
}
